import db from '@/store/localstorage';
const permissions = db.get('PERMISSIONS');

/**
 * 权限检查方法（且把该方法添加到vue原型中）
 * @param value
 * @returns
 */
export const checkPermissions = (value: any) => {
	let isExist = false;
	if (permissions === undefined || permissions == null) {
		return false;
	}
	if (permissions.indexOf(value) >= 0) {
		// 若在按钮中定义的权限字段能在后端返回的权限数组中能找到，则该按钮可显示
		isExist = true;
	}
	return isExist;
};

const permission = {
	init: (app: any) => {
		/** 单个权限 **/
		app.directive('has', {
			mounted(el: any, binding: any, c: any) {
				if (!checkPermissions(binding.value)) {
					el.parentNode.removeChild(el);
				}
			}
		});

		/** 必须同时满足多个权限 **/
		app.directive('has-and', {
			mounted: function (el: any, binding: any, c: any) {
				let sa = binding.value.split('|');
				let res = true;
				sa.forEach((x: any) => {
					if (!checkPermissions(x)) {
						res = false;
					}
				});
				if (!res) {
					el.parentNode.removeChild(el);
				}
			}
		});

		/** 只要满足其中一个权限 **/
		app.directive('has-or', {
			mounted: function (el: any, binding: any, c: any) {
				let sa = binding.value.split('|');
				let res = false;
				sa.forEach((x: any) => {
					if (checkPermissions(x)) {
						res = true;
					}
				});
				if (!res) {
					el.parentNode.removeChild(el);
				}
			}
		});
	},
	install: (app: any) => {
		permission.init(app);
	}
};

export default permission;
